import {defineStore} from "pinia";
import type {TokenInfo} from "@/typings/auth";
import type {SysPermission, SysUser} from "@/typings/sys";

interface AuthState {
    userInfo: SysUser | null;
    token: TokenInfo | null;
    permissions: Array<SysPermission>;
    isSimplePwd: boolean;
    loadRouter: boolean;
}

export const useAuthStore = defineStore('auth-store', {
    state: (): AuthState => ({
        /**
         * 用户信息
         */
        userInfo: null,
        /**
         * token
         */
        token: null,
        /**
         * 权限列表
         */
        permissions: [],
        /**
         * 是否是简单密码
         */
        isSimplePwd: false,
        /**
         * 是否加载路由
         */
        loadRouter: false,
    }),
    getters: {
        isAdmin(state: AuthState): boolean {
            return state.userInfo?.id === 1;
        },
        isLogin(state: AuthState): boolean {
            if (!state.token) {
                return false;
            }
            return state.token.isLogin;
        }
    },
    actions: {
        clearToken() {
            this.token = null;
            this.userInfo = null;
            this.permissions = [];
            this.loadRouter = false;
        }
    },
    persist: {
        pick: ['userInfo', 'permissions', 'token']
    }
})